using Newtonsoft.Json;
using System.Net.Http.Headers;
using System.Threading.Tasks;
using System.Net.Http;

namespace AbpProjectTemplate.Extensions
{
    public static class HttpClientExtensions
    {
        public static async Task<TResult> PostJsonAsync<TResult>(this HttpClient client, string url, object data)
        {
            var strConent = data == null ? "" : JsonConvert.SerializeObject(data);
            var httpContent = new StringContent(strConent);
            httpContent.Headers.ContentType = new MediaTypeHeaderValue("application/json");
            httpContent.Headers.ContentType.CharSet = "utf-8";
            var response = await client.PostAsync(url, httpContent);
            var content = await response.Content.ReadAsStringAsync();
            return JsonConvert.DeserializeObject<TResult>(content);
        }

        public static async Task<TResult> PutJsonAsync<TResult>(this HttpClient client, string url, object data)
        {
            var strConent = data == null ? "" : JsonConvert.SerializeObject(data);
            var httpContent = new StringContent(strConent);
            httpContent.Headers.ContentType = new MediaTypeHeaderValue("application/json");
            //httpContent.Headers.Add("Accept", "application/json");
            httpContent.Headers.ContentType.CharSet = "utf-8";
            var response = await client.PutAsync(url, httpContent);
            var content = await response.Content.ReadAsStringAsync();
            return JsonConvert.DeserializeObject<TResult>(content);
        }

        public static async Task<TResult> GetJsonAsync<TResult>(this HttpClient client, string url)
        {
            var response = await client.GetAsync(url);
            var content = await response.Content.ReadAsStringAsync();
            return JsonConvert.DeserializeObject<TResult>(content);
        }
    }
}
